#!/data/data/com.termux/files/usr/bin/bash
if [ "$(getprop ro.build.version.sdk)" -ge "34" ]; then
  unset LD_LIBRARY_PATH LD_PRELOAD
  export CLASSPATH=/data/data/com.termux/files/usr/libexec/termux-x11/loader.apk
  export TERMUX_X11_LOADER_OVERRIDE_CMDENTRYPOINT_CLASS=com.termux.x11.LoriePreferences\$Receiver
  exec /system/bin/app_process -Xnoimage-dex2oat / com.termux.x11.Loader "$@"
fi

COMMAND=("am" "broadcast" "-a" "com.termux.x11.CHANGE_PREFERENCE" "-p" "com.termux.x11")
help() {
  echo "$0 [list] {key:value} [{key2:value2}]..."
  exit 1
}

list() {
  output="$("${COMMAND[@]}" -e list null 2>&1)"
  result=$(sed -n '/result=[0-9]*/{s/.*result=\([0-9]*\).*/\1/p;q;}' <<< "$output")
  if [[ "$result" == "0" ]]; then
    echo "Something went wrong."
    exit 1
  fi
  if [[ "$result" == "2" ]] || [[ "$result" == "4" ]]; then
    echo "$(echo "$output" | sed -z 's/.*data="\([^"]*\)*/\1/' | sed '${s/"$//}')"
    exit 0
  fi
  echo "list: Unexpected result $result"
  echo "$output"
  exit 1
}

if [ $# -eq 0 ]; then
  if [ -t 0 ]; then
    help
  else
    OLD_LENGTH="${#COMMAND[@]}"
    while IFS= read -r line || [[ -n "$line" ]]; do
      [ -z "$line" ] && continue
      key=$(echo "$line" | sed -E 's/^"([^"]+)".*/\1/')
      value=$(echo "$line" | sed -E 's/^"[^"]+"="(.*)"/\1/')
      COMMAND+=("-e" "$key" "$value")
    done
    if [[ "$OLD_LENGTH" == "${#COMMAND[@]}" ]]; then
      help
    fi
  fi
fi

while [[ $# -gt 0 ]]; do
  case $1 in
    list) list;;
    *:*) COMMAND+=("-e" "${1%%:*}" "${1#*:}");;
    *) echo "Unrecognised option $1"; help
  esac
  shift
done

output="$("${COMMAND[@]}")"
result=$(sed -n '/result=[0-9]*/{s/.*result=\([0-9]*\).*/\1/p;q;}' <<< "$output")
if [[ "$result" == "0" ]]; then
  echo "Something went wrong."
  exit 1
fi

if [[ "$result" == "2" ]] || [[ "$result" == "4" ]]; then
  echo "$(echo "$output" | sed -z 's/.*data="\([^"]*\)*/\1/' | sed '${s/"$//}')"
  exit 0
fi

echo "set: Unexpected result $result"
echo "$output"
exit 1
